import { useReducer } from "react";

const initialState = {
    count1: 0,
    count2: 0,
}

const reducer = (state, action) => {
    switch (action.type) {
        case 'increment1':
            return {
                ...state,
                count1: state.count1 + 1
            };
        case 'increment2':
            return {
                ...state,
                count2: state.count2 + 1
            };

        case 'decrement1':
            return {
                ...state,
                count1: state.count1 - 1
            };
        case 'decrement2':
            return {
                ...state,
                count2: state.count2 - 1
            };
            
        case 'reset1':
            return {
                ...state,
                count1: 0
            };
        case 'reset2':
            return {
                ...state,
                count2: 0
            }
    
        default:
            throw new Error('unExpected action');
    }
}

function Demo () {
    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <div className="border">
            <p className="title">Demo--useReducer--2</p>
            <h1>count1: {state.count1}</h1>
            <h1>count2: {state.count2}</h1>
            <button onClick={() => { dispatch({ type: 'increment1'} ) }}>add1</button>
            <button onClick={() => { dispatch({ type: 'decrement1'} ) }}>minus1</button>
            <button onClick={() => { dispatch({ type: 'reset1'} ) }}>reset1</button>
            <button onClick={() => { dispatch({ type: 'increment2'} ) }}>add2</button>
            <button onClick={() => { dispatch({ type: 'decrement2'} ) }}>minus2</button>
            <button onClick={() => { dispatch({ type: 'reset2'} ) }}>reset2</button>
        </div>
    )
}

export default Demo;